/*
 * IIOPreferencesPane.java
 *
 * Created on September 23, 2004, 9:13 PM
 */

package kiyut.ekspos.prefs;

import java.util.Iterator;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.spi.ImageReaderWriterSpi;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

// TODO: Auto-generated Javadoc
/**
 * The Class IIOPreferencesPane.
 */
public class IIOPreferencesPane extends PreferencesPane {
    
    /** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/**
	 * Instantiates a new iIO preferences pane.
	 */
    public IIOPreferencesPane() {
        initComponents();
        initCustomComponents();
    }
    
    /**
     * Inits the components.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        readerTable = new javax.swing.JTable();

        setLayout(new java.awt.GridBagLayout());

        readerTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Format", "Provider"
            }
        ));
        jScrollPane1.setViewportView(readerTable);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        add(jScrollPane1, gridBagConstraints);

    }//GEN-END:initComponents
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    /** The j scroll pane1. */
    private javax.swing.JScrollPane jScrollPane1;
    
    /** The reader table. */
    private javax.swing.JTable readerTable;
    // End of variables declaration//GEN-END:variables
    
    /**
     * Inits the custom components.
     */
    private void initCustomComponents() {
        IIOTableModel model = new IIOTableModel();
        readerTable.setModel(model);
        TableColumnModel columnModel = readerTable.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(50);
        
        JComboBox editorCombo = new JComboBox();
        editorCombo.setEditable(false);
        columnModel.getColumn(1).setCellEditor(new IIOTableCellEditor(editorCombo));
        
    }
    
    /* (non-Javadoc)
     * @see kiyut.ekspos.prefs.PreferencesPane#loadPrefs()
     */
    public void loadPrefs() {
        // do nothing
        //IIOPreferences prefs = IIOPreferences.getInstance();
    }
    
    /* (non-Javadoc)
     * @see kiyut.ekspos.prefs.PreferencesPane#savePrefs()
     */
    public void savePrefs() {
        IIOPreferences prefs = IIOPreferences.getInstance();
        
        Map<String,ImageReaderSpi> readerMap = prefs.getImageReaderWriterPreferences().getPreferredImageReaderSpi();
        for (int i=0; i<readerTable.getRowCount(); i++) {
            String format = (String)readerTable.getValueAt(i,0);
            String provider = (String)readerTable.getValueAt(i,1);
            ImageReader reader = getImageReader(format,provider);
            if (reader != null) {
                readerMap.put(format,reader.getOriginatingProvider());
            }
        }
        
        prefs.save();
    }
    
    /**
     * Gets the provider name.
     *
     * @param spi the spi
     * @return the provider name
     */
    public static String getProviderName(ImageReaderWriterSpi spi) {
        return spi.getVendorName() + " " + spi.getVersion();
    }
    
    /**
     * Gets the image reader.
     *
     * @param format the format
     * @param provider the provider
     * @return the image reader
     */
    public static ImageReader getImageReader(String format, String provider) {
        ImageReader reader = null;
        Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(format);
        while (it.hasNext()) {
            ImageReader readerTemp = it.next();
            ImageReaderSpi spi = readerTemp.getOriginatingProvider();
            if (spi == null) { continue; }
            String str = getProviderName(spi);
            if (str.equals(provider)) {
                //System.err.println(format + "-" + codec + "-" + str + "-equals");
                reader = readerTemp;
                break;
            }
        }
        return reader;
    }
    
    /**
     * The Class IIOTableModel.
     */
    private static class IIOTableModel extends DefaultTableModel {
        
        /** The Constant serialVersionUID. */
		private static final long serialVersionUID = 1L;

		/**
		 * Instantiates a new iIO table model.
		 */
		public IIOTableModel() {
            // setting column
            addColumn("Format");
            addColumn("Provider");
            
            // setting data
            IIOPreferences prefs = IIOPreferences.getInstance();
            @SuppressWarnings("rawtypes")
			Map readerMap = prefs.getImageReaderWriterPreferences().getPreferredImageReaderSpi();
            @SuppressWarnings("rawtypes")
			Iterator it = readerMap.entrySet().iterator();
            while (it.hasNext()) {
                @SuppressWarnings("rawtypes")
				Map.Entry entry = (Map.Entry)it.next();
                ImageReaderSpi spi = (ImageReaderSpi)entry.getValue();
                String[] dataRow = new String[2];
                dataRow[0] = (String)entry.getKey();
                dataRow[1] = getProviderName(spi);
                addRow(dataRow);
            }
        }
        
        /* (non-Javadoc)
         * @see javax.swing.table.DefaultTableModel#isCellEditable(int, int)
         */
        @Override
        public boolean isCellEditable(int row, int col) {
            boolean b = false;
            if (col == 1) {
                b = true;
            }
            
            return b;
        }
    }
    
    /**
     * The Class IIOTableCellEditor.
     */
    private static class IIOTableCellEditor extends DefaultCellEditor {
        
        /** The Constant serialVersionUID. */
		private static final long serialVersionUID = 1L;

		/**
		 * Instantiates a new iIO table cell editor.
		 *
		 * @param comboBox the combo box
		 */
		public IIOTableCellEditor(JComboBox comboBox) {
            super(comboBox);
        }
        
        /* (non-Javadoc)
         * @see javax.swing.DefaultCellEditor#getTableCellEditorComponent(javax.swing.JTable, java.lang.Object, boolean, int, int)
         */
        @Override
        public java.awt.Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            JComboBox comboBox = (JComboBox)getComponent();
            comboBox.removeAllItems();
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName((String)table.getValueAt(row,0));
            while (it.hasNext()) {
                ImageReaderSpi spi = it.next().getOriginatingProvider();
                comboBox.addItem(getProviderName(spi));
            }
            return super.getTableCellEditorComponent(table, value, isSelected,row, column);
        }
    }
}
